/*
 * Copyright (C) 2015 huwentao.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mokey.core.retrofit.convert.fastjson;

import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

final class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        T t = null;
        BufferedSource source = null;
        try {
            source = Okio.buffer(Okio.source(value.byteStream()));
            String jsonStr = source.readUtf8();
            t = JSON.parseObject(jsonStr, type);
            source.close();
            value.close();
        } catch (Exception e) {
            Log.e(FastJsonResponseBodyConverter.class.getSimpleName(), e.getMessage(), e);
        } finally {
            return t;
        }
    }
}
